from django.http import HttpResponse

from api.paymethod import *
from rest_framework.views import APIView
from api.utils import * 
from api.models import *
from h5api.settings import IMAGE_DOMAIN_NAME,ALIPAY_CALLBACK_URI,XORPAY_CALLBACK_URI
# Create your views here.


#当前是服务商注册接口
class AdminAPIView(APIView):

    def get(self,request,*args, **kwargs):
        serviceProvider_id = request.session.get("serviceProvider_id")
        sp = ServiceProvider.objects.get(pk=serviceProvider_id)
        sp.balance = 10000
        sp.save()
        return resultResponse()

    def post(self,request,*args, **kwargs):
        phone = request.data.get("phone",None)
        if not phone:
            return resultResponse(700,"请输入手机号")
        if ServiceProvider.objects.filter(phone=phone).first():
            return resultResponse(700,"该用户已注册")
        serviceProvider = getClassData(request,["name","phone","password"])
        serviceProvider["password"] = md5(serviceProvider["password"])
        sp = ServiceProvider.objects.create(**serviceProvider)
        request.session["serviceProvider_id"] = sp._id
        return resultResponse()

class SetMealAPIView(APIView):

    def get(self,request,*args, **kwargs):
        #前端展示无需拦截  无需认证
        setmeals = list(SetMeal.objects.all().values())
        for setmeal in setmeals:
            setmeal["divClass"] = "block-plain"
            setmeal["aClass"] = "btn-info"
            setmeal["tableClass"] = ""
        return resultResponse(data=setmeals,_list=True)

    def post(self,request,*args, **kwargs):
        #网站管理员可以添加
        setmeal = getClassData(request,["title","price","domainNameNumber","payMethodNumber","desc"])
        SetMeal.objects.create(**setmeal)
        return resultResponse()

    def put(self,request,*args, **kwargs):
        pass 

    def delete(self,request,*args, **kwargs):
        pass  

class SetMealOrderAPIView(APIView):

    def get(self,request,*args, **kwargs):
        #服务商获取自己的订单信息
        pass 

    def post(self,request,*args, **kwargs):
        #服务商购买
        serviceProvider_id = request.session.get("serviceProvider_id")
        serviceProvider = ServiceProvider.objects.get(pk=serviceProvider_id)
        setmeal_id = request.data.get("setmeal_id",None)
        if not setmeal_id:
            return resultResponse(700,"无订单信息")
        setmeal = SetMeal.objects.get(pk=int(setmeal_id))
        if serviceProvider.balance < setmeal.price:
            return resultResponse(700,"余额不足，请联系管理员充值17744602018")
        serviceProvider.balance = serviceProvider.balance - setmeal.price
        serviceProvider.save()

        #生成订单
        SetMealOrder.objects.create(setmeal=setmeal,serviceProvider=serviceProvider,price=setmeal.price)

        return resultResponse()

class ServiceProviderAPIView(APIView):

    def get(self,request,*args, **kwargs):
        pass 

    def post(self,request,*args, **kwargs):
        phone = request.data.get("phone",None)
        if not phone:
            return resultResponse(700,"请输入手机号")
        if ServiceProvider.objects.filter(phone=phone).first():
            return resultResponse(700,"该用户已注册")
        serviceProvider = getClassData(request,["name","phone","password"])
        serviceProvider["password"] = md5(serviceProvider["password"])
        sp = ServiceProvider.objects.create(**serviceProvider)
        request.session["serviceProvider_id"] = sp._id
        return resultResponse()

    def put(self,request,*args, **kwargs):
        #登录
        phone = request.data.get("phone",None)
        if not phone :
            return resultResponse(700,"无手机号")
        password = request.data.get("password",None)
        if not password:
            return resultResponse(700,"无密码")
        password = md5(password)
        serviceProvider = ServiceProvider.objects.filter(phone=phone).first()
        if not serviceProvider:
            return resultResponse(700,"无该用户")
        if serviceProvider.password != password:
            return resultResponse(700,"用户密码错误")
        request.session["serviceProvider_id"] = serviceProvider._id 
        return resultResponse()

    def delete(self,request,*args, **kwargs):
        pass 

class ConsumerAPIView(APIView):
    
    def get(self,request,*args, **kwargs):
        #获取服务商用户
        pass 

    def post(self,request,*args, **kwargs):
        #消费者登录
        pass 

class ConsumerConsumeAPIView(APIView):

    def get(self,request,*args, **kwargs):
        pass 

    def put(self,request,*args, **kwargs):
        #用户地址填写支付商品 无需拦截
        link_id = request.data.get("link_id",None)
        if not link_id:
            return resultResponse(700,"无分享链接ID")
        link = Link.objects.get(pk=int(link_id))

        #获取商品信息
        goods = link.goods

        #查看是否有库存
        if goods.stock <= 0:
            return resultResponse(700,"暂无库存")

        #创建消费者用户信息
        phone = request.data.get("phone",None)
        if not phone:
            return resultResponse(700,"请填写联系电话")
        consumer = Consumer.objects.filter(phone=phone).first()
        if not consumer:
            consumer = getClassData(request,["name","phone"])
            consumer["password"] = md5(consumer["phone"])
            consumer["court"] = Court.objects.create()
            consumer = Consumer.objects.create(**consumer)
            consumer.serviceProviders.add(link.serviceProvider)
        
        #创建收货地址
        address = getClassData(request,["address","addressDetail","name","phone"])
        address["consumer"] = consumer 
        address = ShoppingAddress.objects.create(**address)

        #生成订单
        consumerOrder = dict()
        consumerOrder["orderNumber"] = createOrderId()
        consumerOrder["status"] = "未发货"
        consumerOrder["payStatus"] = "未支付"
        consumerOrder["consumer"] = consumer
        consumerOrder["link"] = link
        consumerOrder["shoppingAddress"] = address
        consumerOrder = ConsumerOrder.objects.create(**consumerOrder)

        #跟新商品库存信息
        goods.stock = goods.stock - 1 
        goods.save()

        #根据需求生成支付链接
        paymethod = link.paymethod
        payId = link.payId
        payLink = ""
        if paymethod == "支付宝":
            aliPay = AliPay.objects.get(pk=payId) 
            payLink = getPayLinkAliPay(aliPay,goods.sellData(),consumerOrder._id,ALIPAY_CALLBACK_URI)
        elif paymethod == "XorPay":
            payLink="https://mp.yxdlysxh.org.cn/static/goodsimages/alipayqr.png"
            # xorpay = XorPay.objects.get(pk=payId)
            # para = getPayLinkXorPay(xorpay,goods.sellData(),consumerOrder._id,XORPAY_CALLBACK_URI) 
            # if para["status"] == "ok":
            #     payLink = para['info']["qr"]
        else:
            pass 

        return resultResponse(data={"payLink":payLink,"paymethod":paymethod})

    def post(self,request,*args, **kwargs):
        #支付回调
        #goods.sellNumber = goods.sellNumber + 1#这个可以在支付成功后操作
        order_id = request.data.get("more",None)
        if order_id:#这个是xorpay 的
            order = ConsumerOrder.objects.get(pk=int(order_id))
            order.payStatus = "已支付"
            goods = order.link.goods 
            goods.sellNumber= goods.sellNumber + 1
            goods.save()
            order.save()
        else:
            out_trade_no = request.data.get("out_trade_no",None)#数据库中的_id  out_trade_no54
            trade_no = request.data.get("trade_no",None)#trade_no2022011622001492041409534372
            trade_status = request.data.get("trade_status",None)#trade_statusTRADE_SUCCESS
            order = ConsumerOrder.objects.get(pk=int(out_trade_no))
            if trade_status == "TRADE_SUCCESS":
                order.payStatus = "已支付"
                goods = order.link.goods 
                goods.sellNumber= goods.sellNumber + 1
                goods.save()
                order.save()

        link = order.link
        link.linkSellNumber = link.linkSellNumber + 1
        link.save()

        consumerName = order.shoppingAddress.name 
        recicePhoneNum = order.shoppingAddress.phone
        orderNumber = order.orderNumber
        sendPhoneTextMessage(consumerName,orderNumber,"q:1279358927",recicePhoneNum)
        return HttpResponse("success")
       

class AliPayAPIView(APIView):

    def get(self,request,*args, **kwargs):
        #服务商获取自己的支付宝支付信息    在xorpay中实现
        pass 

    def delete(self,request,*args, **kwargs):
        _id = request.data.get("_id")
        AliPay.objects.filter(pk=int(_id)).delete()
        return resultResponse()

    def post(self,request,*args, **kwargs):
        serviceProvider_id = request.session["serviceProvider_id"] 
        setmealorder = SetMealOrder.objects.filter(serviceProvider_id=serviceProvider_id).last()
        if not setmealorder:
            return resultResponse(700,"您还为购买套餐请联系17744602018购买")
        setmeal = setmealorder.setmeal
        alipayNum = AliPay.objects.filter(serviceProvider_id=serviceProvider_id).count()
        xorpayNum = XorPay.objects.filter(serviceProvider_id=serviceProvider_id).count()
        if setmeal.payMethodNumber <= (alipayNum+xorpayNum):
            return resultResponse(700,"您可添加的账号个数为"+str(setmeal.payMethodNumber))

        aliapy = getClassData(request,["serviceProviderName","account","appId","publicKey","privateKey"])
        aliapy["serviceProvider_id"] = serviceProvider_id
        AliPay.objects.create(**aliapy)
        return resultResponse()

class XorPayAPIView(APIView):

    def get(self,request,*args, **kwargs):
        #服务商获取自己的Xorpay支付信息
        serviceProvider_id = request.session["serviceProvider_id"] 
        alipays = list(AliPay.objects.filter(serviceProvider___id=serviceProvider_id).values("_id","createTime","serviceProviderName","account"))
        for ali in alipays:
            ali["type"] = "支付宝"
        xorpays = list(XorPay.objects.filter(serviceProvider___id=serviceProvider_id).values("_id","createTime","serviceProviderName","account"))
        for xor in xorpays:
            xor["type"] = "XorPay"
        return resultResponse(data=xorpays+alipays,_list=True)

    def post(self,request,*args, **kwargs):
        serviceProvider_id = request.session["serviceProvider_id"] 
        setmealorder = SetMealOrder.objects.filter(serviceProvider_id=serviceProvider_id).last()
        if not setmealorder:
            return resultResponse(700,"您还为购买套餐请联系17744602018购买")
        setmeal = setmealorder.setmeal
        alipayNum = AliPay.objects.filter(serviceProvider_id=serviceProvider_id).count()
        xorpayNum = XorPay.objects.filter(serviceProvider_id=serviceProvider_id).count()
        if setmeal.payMethodNumber <= (alipayNum+xorpayNum):
            return resultResponse(700,"您可添加的账号个数为"+str(setmeal.payMethodNumber))
        
        xorpay = getClassData(request,["serviceProviderName","account","appId","privateKey"])
        xorpay["serviceProvider_id"] = serviceProvider_id
        XorPay.objects.create(**xorpay)
        return resultResponse()

    def delete(self,request,*args, **kwargs):
        _id = request.data.get("_id")
        XorPay.objects.filter(pk=int(_id)).delete()
        return resultResponse()

class DomainNameAPIView(APIView):

    def get(self,request,*args, **kwargs):
        domainnames = list(DomainName.objects.all().values())
        return resultResponse(data=domainnames,_list=True)

    def post(self,request,*args, **kwargs):
        domainname = getClassData(request,["domainname","price","desc"])
        DomainName.objects.create(**domainname)
        return resultResponse()

class DomainNameOrderAPIView(APIView):

    def get(self,request,*args, **kwargs):
        serviceProvider_id = request.session.get("serviceProvider_id")
        domainnames = list(DomainNameOrder.objects.filter(serviceProvider_id=serviceProvider_id).values("_id","createTime","domainname__domainname")) 
        return resultResponse(data=domainnames,_list=True)

    def post(self,request,*args, **kwargs):
        #服务商购买
        serviceProvider_id = request.session.get("serviceProvider_id")
        serviceProvider = ServiceProvider.objects.get(pk=serviceProvider_id)
        domainname_id = request.data.get("domainname_id",None)
        if not domainname_id:
            return resultResponse(700,"无订单信息")
        domainname = DomainName.objects.get(pk=int(domainname_id))
        if serviceProvider.balance < domainname.price:
            return resultResponse(700,"余额不足，请联系管理员充值17744602018")
        serviceProvider.balance = serviceProvider.balance - domainname.price
        serviceProvider.save()

        #生成订单
        DomainNameOrder.objects.create(domainname=domainname,serviceProvider=serviceProvider)

        return resultResponse()

    def delete(self,request,*args, **kwargs):
        _id = request.data.get("_id",None)
        if not _id:
            return resultResponse(204)
        DomainNameOrder.objects.filter(pk=int(_id)).delete()
        return resultResponse()

class HelpDocumentAPIView(APIView):

    def get(self,request,*args, **kwargs):
        helps = list(HelpDocument.objects.all().values())
        return resultResponse(data=helps,_list=True)

    def post(self,request,*args, **kwargs):
        help = getClassData(request,["content"])
        HelpDocument.objects.create(**help)
        return resultResponse()

class GoodsAPIView(APIView):
    pass 

class LinkUpdateAPIView(APIView):

    def post(self,request,*args, **kwargs):
        _id = request.data.get("_id",None)
        paymethod = request.data.get("paymethod",None)
        payId = request.data.get("payId",None)
        if not _id or not paymethod or not payId:
            return resultResponse(204)
        Link.objects.filter(pk=int(_id)).update(payId=int(payId),paymethod=paymethod)
        return resultResponse()

class LinkAPIView(APIView):

    def get(self,request,*args, **kwargs):
        #获取服务商自己的链接
        serviceProvider_id = request.session.get("serviceProvider_id")
        links = list(Link.objects.filter(serviceProvider_id=serviceProvider_id).values("_id","title","createTime","domainname","paymethod","goods__goodsName","goods__sellPrice","goods__originPrice","goods__stock","goods__sellNumber"))
        return resultResponse(data=links,_list=True)


    def post(self,request,*args, **kwargs):
        #创建链接
        link = dict()
        link["h5template_id"] = request.data.get("h5Template_id",None)
        if not link["h5template_id"]:
            return resultResponse(700,"无模板信息")
        link["domainname"] = request.data.get("domainname",None)
        if not link["domainname"]:
            return resultResponse(700,"无域名信息")
        link["paymethod"] = request.data.get("paymethod",None)
        if not link["paymethod"]:
            return resultResponse(700,"无支付方式")
        link["payId"] = request.data.get("payId",None)
        if not link["payId"]:
            return resultResponse(700,"无支付ID")
        link["title"] = request.data.get("title",None)
        if not link["title"]:
            return resultResponse(700,"无标题")
        link["serviceProvider_id"] = request.session.get("serviceProvider_id",None)
        
        goods = getClassData(request,["goodsName","sellPrice","originPrice","stock","detail"])
        goods["image1"] = request.FILES.get("image1",None)
        goods["image2"] = request.FILES.get("image2",None)
        goods["image3"] = request.FILES.get("image3",None)
        goods["image4"] = request.FILES.get("image4",None)
        goods["image5"] = request.FILES.get("image5",None)

        goods = Goods.objects.create(**goods)

        link["goods"] = goods
        link = Link.objects.create(**link)

        return resultResponse()

    def delete(self,request,*args, **kwargs):
        serviceProvider_id = request.session.get("serviceProvider_id",None) 
        if serviceProvider_id != 2:
            return resultResponse(700,"暂时无法删除")
        linkId = request.data.get("linkId",None)
        if not linkId:
            return resultResponse(700,'没有linkId')
        Link.objects.filter(pk=int(linkId)).delete() 
        return resultResponse()

    def put(self,request,*args, **kwargs):
        #拷贝某个链接  重新定义名字
        newTitle = request.data.get("newTitle",None)
        link_id = request.data.get("link_id",None)
        if not link_id:
            return resultResponse(700,"无链接ID")
        link = Link.objects.get(pk=int(link_id))
        link.pk = None
        link.title = newTitle
        link.linkSellNumber = 0
        link.save()

        return resultResponse()

class H5TemplateShowDataAPIView(APIView):

    def get(self,request,*args, **kwargs):
        #获取某个链接的所有内容用于h5显示  无需拦截
        link_id = request.GET.get("linkId")
        link = Link.objects.get(pk=link_id)
        goods = link.goods
        link = {
            "title":link.title,
            "goodsName":goods.goodsName,
            "sellPrice":goods.sellPrice,
            "originPrice":goods.originPrice,
            "stock":goods.stock,
            "sellNumber":goods.sellNumber,
            "detail":goods.detail,
            "images":[],
            "linkSellNumber":link.linkSellNumber,
            "_id":goods._id#注意这是商品的ID
        }
        if goods.image1:
            link["images"].append(IMAGE_DOMAIN_NAME+str(goods.image1))
        if goods.image2:
            link["images"].append(IMAGE_DOMAIN_NAME+str(goods.image2))
        if goods.image3:
            link["images"].append(IMAGE_DOMAIN_NAME+str(goods.image3))
        if goods.image4:
            link["images"].append(IMAGE_DOMAIN_NAME+str(goods.image4))
        if goods.image5:
            link["images"].append(IMAGE_DOMAIN_NAME+str(goods.image5))

        return resultResponse(data=link)
          
class H5TemplateAPIView(APIView):

    def get(self,request,*args, **kwargs):
        #无需拦截
        h5temps = list(H5Template.objects.all().values())
        return resultResponse(data=h5temps,_list=True)

    def post(self,request,*args, **kwargs):
        #创建模板信息
        h5temp = getClassData(request,["title","price","desc"])
        H5Template.objects.create(**h5temp)
        return resultResponse()

class H5TemplateOrderAPIView(APIView):
    
    def get(self,request,*args, **kwargs):
        #获取自己的订单信息
        serviceProvider_id = request.session.get("serviceProvider_id")
        templates = list(H5TemplateOrder.objects.filter(serviceProvider_id=serviceProvider_id).values("_id","createTime","h5template__title","h5template__desc"))
        return resultResponse(data=templates,_list=True)

    def post(self,request,*args, **kwargs):
        #服务商购买现
        serviceProvider_id = request.session.get("serviceProvider_id")
        serviceProvider = ServiceProvider.objects.get(pk=serviceProvider_id)
        h5template_id = request.data.get("h5template_id",None)
        if not h5template_id:
            return resultResponse(700,"无订单信息")
        h5template = H5Template.objects.get(pk=int(h5template_id))
        if serviceProvider.balance < h5template.price:
            return resultResponse(700,"余额不足，请联系管理员充值17744602018")
        serviceProvider.balance = serviceProvider.balance - h5template.price
        serviceProvider.save()

        #生成订单
        H5TemplateOrder.objects.create(h5template=h5template,serviceProvider=serviceProvider)

        return resultResponse()

    def delete(self,request,*args, **kwargs):
        _id = request.data.get("_id",None)
        if not _id:
            return resultResponse(204)
        H5TemplateOrder.objects.filter(pk=int(_id)).delete()
        return resultResponse()

class ConsumerOrderAPIView(APIView):

    def get(self,request,*args, **kwargs):
        link_id = int(request.GET.get("linkId",0))
        link = list(Link.objects.filter(pk=link_id).values("title","_id","domainname","goods__goodsName","goods__sellPrice"))[0]
        link["order"] = list(ConsumerOrder.objects.filter(link_id=link["_id"]).values("_id","payStatus","status","createTime","shoppingAddress__name","shoppingAddress__phone","orderNumber","shoppingAddress__address","shoppingAddress__addressDetail",))
        if link["order"]:
            for order in link["order"]:
                order["createtime"]=order["createTime"],
                order["name"]=order["shoppingAddress__name"],
                order["phone"]=order["shoppingAddress__phone"],
                order["ordernumber"]=order["orderNumber"],
                order["address"]=order["shoppingAddress__address"],
                order["detail"]=order["shoppingAddress__addressDetail"],
        return resultResponse(data=link)

    #获取用户当前界面最新的订单信息 需要传递参数rightNowConsumerOrderId
    def put(self,request,*args, **kwargs):
        rightNowConsumerOrderId = request.data.get("rightNowConsumerOrderId",None)
        if not rightNowConsumerOrderId:
            return resultResponse(700,"缺少rightNowConsumerOrderId")
        link_id = int(request.data.get("linkId",0))
        link = list(Link.objects.filter(pk=link_id).values("title","_id","domainname","goods__goodsName","goods__sellPrice"))[0]
        link["order"] = list(ConsumerOrder.objects.filter(_id__gt=rightNowConsumerOrderId,link_id=link["_id"]).values("_id","payStatus","status","createTime","shoppingAddress__name","shoppingAddress__phone","orderNumber","shoppingAddress__address","shoppingAddress__addressDetail",))
        if link["order"]:
            for order in link["order"]:
                order["createtime"]=order["createTime"],
                order["name"]=order["shoppingAddress__name"],
                order["phone"]=order["shoppingAddress__phone"],
                order["ordernumber"]=order["orderNumber"],
                order["address"]=order["shoppingAddress__address"],
                order["detail"]=order["shoppingAddress__addressDetail"],
        return resultResponse(data=link)

    def post(self,request,*args, **kwargs):
        order_id = request.data.get("orderId",None)
        if not order_id:
            return resultResponse(700,"无订单信息")
        ConsumerOrder.objects.filter(pk=int(order_id)).update(status="运输中")
        return resultResponse()